#include "form.h"
#include "ui_form.h"
#include <QDebug>
#include "aip-cpp-sdk/face.h"

using namespace std;
extern QTcpSocket *client;
string app_id = "19274994";
string api_key = "56TWbxryLVDUfRAvmiztCIg5";
string secret_key = "D0vFKvIDbmEKgn550GEC9ZPNjpKqAgqR";
// 人脸识别登录
aip::Face client_m(app_id, api_key, secret_key);


Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);
    connect(ui->pushButton_back,SIGNAL(clicked()),this,SLOT(sendInsertSignal()));

}

Form::~Form()
{
    delete ui;
}

void Form::on_pushButton_2_clicked()
{
    //将员工信息写入root
    root["cmd"] = "insertEmployee_req";
    root["name"] = ui->lineEdit_name->text().toStdString();
    root["employeeid"] = ui->lineEdit_id->text().toStdString();
    root["sex"] = ui->lineEdit_sex->text().toStdString();
    root["phone"] = ui->lineEdit_phone->text().toStdString();
    root["time"] = ui->lineEdit_time->text().toStdString();
    root["position"] = ui->lineEdit_position->text().toStdString();
    root["department"] = ui->lineEdit_department->text().toStdString();
    root["email"] = ui->lineEdit_email->text().toStdString();
    //将员工信息发送给服务器
    qDebug() << root.toStyledString().c_str();
    client->write(writer.write(root).c_str());

    //等待服务器回应是否注册成功，成功弹出注册成功提示框，失败弹出注册失败原因
    client->waitForReadyRead(100);//阻塞等待read
    client->read(jsonstr, sizeof(jsonstr));
    reader.parse(jsonstr,root);
    qDebug() << root.toStyledString().c_str();
    if(strcmp(root["cmd"].asString().c_str(), "insertEmployee_OK") == 0){

        //将人脸图片添加到人脸库
        Json::Value json = client_m.user_add(ba.toBase64().toStdString(), "BASE64" ,"group",ui->lineEdit_id->text().toStdString().c_str() ,aip::null);
        //判断添加是否成功
        if(json["error_code"].asInt())
        {
           qDebug()  << json["error_msg"].toStyledString().c_str();
        }
        QMessageBox::information(this, "注册成功", "员工信息已成功录入", QMessageBox::Yes, QMessageBox::Yes);
    }else{       
        QMessageBox::warning(this, "注册失败", root["cmd"].asString().c_str(), QMessageBox::Yes, QMessageBox::Yes);
    }
}


void Form::on_pushButton_clicked()
{
    //通过按钮打开文件界面并选择图片

    file_full = QFileDialog::getOpenFileName(this);
    fi = QFileInfo(file_full);
    //获取选则图片的绝对路径
    file_path = fi.absolutePath().arg("/");
    file_path.append("/");
    file_path.append(fi.fileName());
    ui->lineEdit_path->setText(file_path);

    //将图片输出为base64格式并写入root
    QImage image(file_path);
    QBuffer buf(&ba);
    image.save(&buf, "jpg");
    buf.close();
}

void Form::sendInsertSignal()
{
    this->close();
    emit insertSignal();
}

void Form::deleteFace(string s){
    client_m.user_delete("group", s.c_str(), aip::null);
}
